<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
    <title>交易监控项目</title>
    <style>
        .sound_alert_container {
            display:none;
        }
    </style>
</head>
<body>

<div class="container" style="max-width: 1000px;">

    <h1 class="text-center my-5">行情监控</h1>

    <div id="inputs">
        <div class="row justify-content-center gap-3">

            <input type="text" class="form-control col-md-3 mb-3" style="flex:1;" placeholder="请输入币种代码,例如BTC"/>

            <input type="text" class="form-control col-md-3 mb-3" style="flex:1;" placeholder="请输入倍数，例如0.006" />

            <button type="button" class="btn btn-primary col-md-3 mb-3" style="flex:1;" onclick="startnow(this);">确认开始</button>

            <button type="button" class="btn btn-primary col-md-3 mb-3" style="flex:1;" onclick="deleteRow(this);">删除币种</button>

        </div>
    </div>
    <button type="button" class="btn btn-primary col-md-3 mb-3" onclick="add_input_rows()">添加币种</button>

    <div id="trade_table">
        <h1 class="text-center my-5">行情展示</h1>
    </div>

</div>

<div class="container sound_alert_container" style="max-width: 1000px;">
    <audio controls id="sound_alert">
        <source src="/static/alert.mp3" type="audio/mpeg" muted="muted" autoplay loop>
        Your browser does not support the audio element.
    </audio>
</div>



<script>


    function add_input_rows() {
        const inputs = document.getElementById("inputs");
        const row = document.createElement("div");
        row.className = "row justify-content-center gap-3";
        row.innerHTML = `
                <input type="text" class="form-control col-md-3 mb-3" style="flex:1;" placeholder="请输入币种代码,例如BTC"/>
                <input type="text" class="form-control col-md-3 mb-3" style="flex:1;" placeholder="请输入倍数，例如0.006" />
                <button type="button" class="btn btn-primary col-md-3 mb-3" style="flex:1;" onclick="startnow(this);">确认开始</button>
                <button type="button" class="btn btn-primary col-md-3 mb-3" style="flex:1;" onclick="deleteRow(this);">删除币种</button>
            `;
        inputs.appendChild(row);
    }

    function deleteRow(button)
    {
        const inputs = document.getElementById("inputs");
        const parent = button.parentElement;
        inputs.removeChild(parent)
        //remove corresponding table
        const table = document.getElementById(parent.id);
        const trade_table = document.getElementById("trade_table");
        if(table){
            trade_table.removeChild(table);
        }
    }

    function formatNumber(number) {
        if (number >= 1000000) {
            return (number / 1000000).toFixed(2) + 'm';
        } else if (number >= 1000) {
            return (number / 1000).toFixed(2) + 'k';
        } else {
            return number.toFixed(2).toString();
        }
    }

    function add_trade_table(table_id)
    {
        const trade_table = document.getElementById("trade_table");
        const table = document.createElement("table");
        table.className = "table table-striped table-hover table-bordered my-3";
        table.id = table_id;
        table.innerHTML = `
        <thead>
            <tr>
                <th>币种</th>
                <th>瞬时交易量</th>
                <th>24小时交易量</th>
                <th>倍数</th>
            </tr>
        </thead>
        <tbody></tbody>
    `;
        trade_table.appendChild(table);
    }

    function play_audio()
    {
        document.querySelector(".sound_alert_container").style.display = "block";
        document.getElementById("sound_alert").play();
    }

    async function get_second_trade_volume(currency)
    {
        const apiBaseUrl = '/api/trade/'+currency;
        const response = await fetch(apiBaseUrl);
        const trade = await response.json();
        const tradepairs = trade.data
        const volCcy24h = Math.floor(tradepairs[0]['volCcy24h'])
        const price_last = Math.floor(volCcy24h * tradepairs[0]['last'])
        const volumne = volCcy24h*price_last
        return {"formatted":formatNumber(volumne), "original":volumne}
    }


    function startnow(button)
    {
        const parent_element = button.parentElement;
        let firstInput = parent_element.querySelector('input[type="text"]:first-child');
        let secondInput = parent_element.querySelector('input[type="text"]:nth-child(2)');

        const currency = firstInput.value;
        const times = secondInput.value;


        if(currency === "")
        {
            alert("请输入币种代码");
            return;
        }

        if(times === "")
        {
            alert("请输入倍数");
            return;
        }

        const subscribeRequest = {
            op: 'subscribe',
            args: [
                {
                    channel: 'candle1s',
                    instId: currency+'-USDT-SWAP'
                }
            ]
        };

        let ws = null;

        add_trade_table(currency+'-USDT-SWAP');

        if (ws !== null && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(subscribeRequest));
        }

        const wsEndpoint = 'wss://ws.okx.com:8443/ws/v5/business';

        ws = new WebSocket(wsEndpoint);

        ws.onopen = function(event) {
            ws.send(JSON.stringify(subscribeRequest));
        };

        let recentRecords = [];

        ws.onmessage = async function(event) {

            const trade_volume = await get_second_trade_volume(currency);
            let original = trade_volume.original
            let tradeVolume = trade_volume.formatted

            try {
                let jsonData = JSON.parse(event.data);
                let table_id = jsonData.arg.instId
                let trade_volume_second = formatNumber(jsonData.data[0][7] * times)

                if(table_id === currency+"-USDT-SWAP")
                {
                    let row = `<tr>
                    <td>${currency}</td>
                    <td>${formatNumber(jsonData.data[0][7] * times)}</td>
                    <td>${tradeVolume}</td>
                    <td>${times}</td>
                    </tr>
                `;

                    recentRecords.unshift(row);

                    recentRecords = recentRecords.slice(0, 3);

                    let tableBody = document.querySelector("#" + table_id + " tbody");
                    tableBody.innerHTML = "";

                    recentRecords.forEach(record => {
                        tableBody.innerHTML += record;
                    });
                }

                if(trade_volume_second > original){
                    play_audio();
                }
            } catch (error) {
                console.error("Error parsing JSON:", error);
            }
        }

        button.disabled = true;
    }


</script>
</body>
</html>